package com.topisv.tms.task.prioritySend;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import javax.persistence.OptimisticLockException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.OptimisticLockingFailureException;

import com.topisv.tms.entity.OrderBackTask;
import com.topisv.tms.service.prioritySend.OrderBackTaskProcessService;
import com.topisv.tms.service.prioritySend.OrderBackTaskService;
import com.topisv.tms.utils.enums.TaskStatus;

public class OrderBackTaskWorker extends Thread {
	private Logger logger = LoggerFactory.getLogger(getClass());
    private BlockingQueue<OrderBackTask> taskQueue = new ArrayBlockingQueue<OrderBackTask>(1000);
    
	private OrderBackTaskService taskService;
    private OrderBackTaskProcessService taskProcessService;
	
	public OrderBackTaskWorker(BlockingQueue<OrderBackTask> taskQueue, OrderBackTaskService taskService, OrderBackTaskProcessService taskProcessService) {
		this.taskQueue = taskQueue;
		this.taskService = taskService;
		 this.taskProcessService = taskProcessService;
	}

	@Override
	public void run() {
		while (true) {
			OrderBackTask task = null;
			try {
				task = taskQueue.take();
				if (task != null) {
				    //检查是否已消费
//                    boolean isProcessed = taskService.findIfProcessed(task.getId());
//                    if (isProcessed) {
//                        continue;
//                    }
                    
                    //开始处理,订单回传
                    taskProcessService.process(task);
				}
			} catch (Exception e) {
//				if(!(e.getCause() instanceof OptimisticLockException) && !(e instanceof OptimisticLockingFailureException)){
//					logger.error(new StringBuilder("[").append(task != null ? task.getId() : null).append("]").append(" case some error.").toString(), e);
//				}
				logger.error("{}=天天订单回传接口失败={}", task.getType() + task.getRelatedNo(), e);
				if (task != null) {
					taskProcessService.updateData(task,"fail");
				}
			}
		}
	}

}
